package cn.kgc.springboot.controller;

import cn.kgc.springboot.entity.Student;
import cn.kgc.springboot.http.ResponseResult;
import cn.kgc.springboot.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author 课工场
 * @date 2025/1/7
 * @description
 */
@RestController
@RequestMapping("student")
@CrossOrigin  // 允许跨域请求
public class StudentController {

    @Resource
    private StudentService studentService;

    // 分页
    @PostMapping("page")
    public ResponseResult studentPage(@RequestBody HashMap<String, Object> params) {

        // 获取当前页的页码
        Integer page = (Integer) params.get("page");
        // 获取每页展示的条数
        Integer limit = (Integer) params.get("limit");

        // 获取搜索关键词数据
        Object name = params.get("name");
        Object clazz = params.get("clazz");


        // 创建分页对象
        Page<Student> studentPage = new Page<>(page, limit);
        // 构建搜索条件
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(ObjectUtils.isNotNull(name), Student::getName, name)
                .eq(ObjectUtils.isNotNull(clazz), Student::getClazz, clazz)
                .orderByDesc(Student::getId);

        studentService.page(studentPage, lambda);

        long total = studentPage.getTotal();
        List<Student> records = studentPage.getRecords();

        return ResponseResult.success().data("total", total).data("tableData", records);
    }

    // 添加学生信息
    @PostMapping("add")
    public ResponseResult addStudent(@RequestBody Student student) {

        // 1. 获取添加学生的学号 判定是否重复
        String studentNo = student.getStudentNo();
        LambdaQueryWrapper<Student> lambda = new QueryWrapper<Student>().lambda();
        lambda.eq(Student::getStudentNo,studentNo);
        Student one = studentService.getOne(lambda);

        // 判定学号是否已经被使用
        if (ObjectUtils.isNotNull(one)){
            return ResponseResult.fail().message("学号已经存在");
        }

        // 添加学生信息
        studentService.save(student);
        return ResponseResult.success();
    }


    // 编辑学生信息
    @PostMapping("edit")
    public ResponseResult editStudent(@RequestBody Student student) {

        studentService.updateById(student);

        return ResponseResult.success();
    }

    // 批量删除
    @PostMapping("batchDelete")
    public ResponseResult batchDelete(@RequestBody List<Integer> ids){

        studentService.removeByIds(ids);

        return  ResponseResult.success();
    }

}
